package com.zqs.takeredpackage.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.zqs.takeredpackage.entity.User;
import com.zqs.takeredpackage.util.UserStoreUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.UUID;

@RestController
@RequestMapping("/user/")
public class UserController {

    private static final UserStoreUtil userStoreUtil = new UserStoreUtil();

    @RequestMapping("doLogin")
    public SaResult doLogin(String account, String password) {
        User user = userStoreUtil.getUser(account);
        if (user == null ) {
            return SaResult.error("用户不存在！");
        }
        if (!user.getPassword().equals(password)) {
            return SaResult.error("密码错误！");
        }
        StpUtil.login(user.getId());
        return SaResult.ok("登录成功！").setData(StpUtil.getTokenInfo());
    }

    //注册
    @RequestMapping("doRegister")
    public SaResult doRegister(String username, String account, String password) {
        if (userStoreUtil.hasUser(account)) {
            return SaResult.error("账号已存在！");
        }
        if(userStoreUtil.hasUserByUsername(username)){
            return SaResult.error("用户名已存在！");
        }
        if (username == null || account == null || password == null) {
            return SaResult.error("请填写完整信息！");
        }
        if (username.length() > 20 || account.length() > 20 || password.length() > 20) {
            return SaResult.error("信息过长！");
        }
        userStoreUtil.addUser(new User(UUID.randomUUID().toString(), username, account, password, new BigDecimal("200")));
        return SaResult.ok("注册成功！");
    }
    //登录信息
    @RequestMapping("getInfo")
    public SaResult getInfo() {
        User user = userStoreUtil.getUserById(StpUtil.getLoginId().toString());
        return SaResult.ok("获取成功！").setData(user);
    }
    //登出
    @RequestMapping("logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok("注销成功！");
    }
}
